import { createClass, registerClass } from "../../../cfw/tools/class_decorator";
import { SDKAdParam, SDKState } from "../../SDKDefine";
import { BaseAdMgr } from "../base/BaseAdMgr";
import { IAdAdapter } from "../base/IAdAdapter";

@registerClass('ArrayAdMgr')
export class ArrayAdMgr extends BaseAdMgr {
    protected ads: IAdAdapter[] = [];

    put(ad: IAdAdapter) {
        this.ads.push(ad)
    }

    has() {
        return this.ads.length > 0
    }

    open(param: SDKAdParam): void {
        let index = param.index;
        let ad = this.ads[index]
        if (ad) {
            if (this.getCurIndex() != param.index) {
                this.destroy()
                this.setCurIndex(param.index)
            }
            ad.setParam(param)
            ad.open()
        }
    }

    get(index: number = this.curIndex) {
        return this.ads[index]
    }

    destroy() {
        if (this.ads[this.curIndex]) {
            this.ads[this.curIndex].destroy()
        }
    }

    close(index: number): void {
        if (this.ads[index]) {
            this.ads[index].close()
        }
    }


    init() {
        if (this.cfg && this.cfg.className) {
            for (let index = 0; index < this.data.length; index++) {
                const element = this.data[index];
                let ins: IAdAdapter = createClass(this.cfg.className)
                if (ins) {
                    ins.setID(element)
                    ins.setSystem(this.getSystem())
                    ins.init()
                    this.put(ins)
                }
            }

        }
    }
}